const Database = require('better-sqlite3')
const crypto = require('crypto')
const db = new Database( 'app.db')

// 简单的密码哈希函数
const hashPassword = (password) => {
    return crypto.createHash('sha256').update(password).digest('hex');
};

// 插入新用户
const password = 'ddd'; // 这是您想要为用户设置的密码
const hashedPassword = hashPassword(password);

const adminExists = db.prepare('SELECT COUNT(*) AS count FROM users WHERE login_name = ?').get('admin');

if (adminExists.count === 0) {
    // 'admin' 用户不存在，可以插入
    const insertUser = db.prepare(`
      INSERT INTO users (login_name, password) VALUES (?, ?)
    `);
    const info = insertUser.run('admin', hashedPassword);
    
} else {
    // 'admin' 用户已存在，不执行插入操作
    
}


const createUser = (login_name, password) => {
    try {
        // 检查用户名是否已存在
        const userExists = db.prepare('SELECT COUNT(*) AS count FROM users WHERE login_name = ?').get(login_name);
        if (userExists.count > 0) {
            return { status: 1, msg: 'Username already exists' };
        }
        const hashedPassword = hashPassword(password)

        // 插入新用户
        const statement = db.prepare('INSERT INTO users (login_name, password) VALUES (?, ?)');
        const info = statement.run(login_name, hashedPassword);
        if (info.changes > 0) {
            return { status: 0, msg: 'User created successfully', userId: info.lastInsertRowid };
        } else {
            return { status: 1, msg: 'Failed to create user' };
        }
    } catch (e) {
        return { status: 1, msg: e.message };
    }
};

const findUserByUsername = (login_name) => {
    try {
        const statement = db.prepare('SELECT * FROM users WHERE login_name = ?');
        const user = statement.get(login_name);
        return user;
    } catch (e) {
        return null;
    }
};


module.exports = { createUser, findUserByUsername }